package net.cattaka.teamredwhite;

import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.util.Map;

import net.cattaka.teamredwhite.web.AssetsContent;
import net.cattaka.teamredwhite.web.ContentWriter;
import net.cattaka.teamredwhite.web.ImageContent;
import net.cattaka.teamredwhite.web.ImageListContent;
import net.cattaka.teamredwhite.web.MessageContent;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class TeamRedWhite extends Activity {
	public static final String IMAGE_PATH = "redwhite_imgs";
	
	private HTTPServer mServer;

	/**
	 * Create処理
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.main);

		// サーバ開始
		try {
			mServer = new HTTPServer();
			mServer.listen();

			AssetsContent assetsContent = new AssetsContent(this);
			assetsContent.setFile("index.html");
			assetsContent.setMime("text/html");
			mServer.addHandler("/index.html", assetsContent);
				
			AssetsContent assetsContent2 = new AssetsContent(this);
			assetsContent2.setFile("upload.html");
			assetsContent2.setMime("text/html");
			mServer.addHandler("/upload.html", assetsContent2);
				
			ImageListContent imageListContent = new ImageListContent(this);
			imageListContent.setPath(IMAGE_PATH);
			imageListContent.setMime("application/json");
			mServer.addHandler("/imagelist.do", imageListContent);
				
			ImageContent imageContent = new ImageContent(this);
			mServer.addHandler("/image.do", imageContent);
			
			MessageContent messageContent = new MessageContent(this);
			mServer.addHandler("/message.do", messageContent);
			
//			mServer.addHandler("/test", new HTTPServer.HTTPHandler() {
//					public void handle(String path, Map<String,String> param, Reader stdin, OutputStream stdout) {
//						
//						try {
//							OutputStreamWriter output = new OutputStreamWriter(stdout);
//							output.write("HTTP/1.0 200 OK\r\n");
//							output.write("Content-Type: text/plain\r\n");
//							output.write("\r\n");
//							output.write("OK");
//							output.flush();
//						} catch (java.io.IOException e) {
//						}
//					}
//				});

		} catch (Exception e) {
			// どうしようもねー
			android.util.Log.e("TestActivity", e.toString());
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		((TextView)findViewById(R.id.ipaddr_text)).setText("IPアドレス : " + HTTPServer.getIPAddress());
	}
	
	/**
	 * Destroy処理
	 */
	@Override
	public void onDestroy() {
		super.onDestroy();

		if (mServer != null) {
			mServer.close();
			mServer = null;
		}
	}
}